<?php

namespace ShowStop\UserBundle\Security\User\Provider;

use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use ShowStop\UserBundle\Entity\User;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class UserProvider implements UserProviderInterface
{
	protected $userManager;
	
	public function __construct($userManager)
	{
		$this->userManager = $userManager;
	}
	
	public function loadUserByUsername($username) {
		$user =  $this->userManager
		->createQuery("SELECT u FROM
	         ShowStopUserBundle:User u
	         WHERE ( u.username = :username
	         OR u.email = :username )
	         AND u.enabled = :enabled")
		->setParameters(array(
	                       'username' => $username,
							'enabled' => 'Y'
		))
		->getOneOrNullResult();
		
		if( empty( $user ) ) {
			throw new UsernameNotFoundException('Cannot log in.');
		}
		
		$roles = $user->getUserRoles();
		if(  $roles[0]->getName() == 'ROLE_BANNED' )
			throw new UsernameNotFoundException('Banned.');
		
		return $user;
	}
	
	public function refreshUser(UserInterface $user) {
		return $this->loadUserByUsername($user->getUsername());
	}
	
	public function supportsClass($class) {
		return $class === 'ShowStop\UserBundle\Entity\User';
	}
}

?>